package 集合.日常使用;

import lombok.Builder;
import lombok.Data;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description
 *
 * @Author: SunAo
 * @Date: 2021/9/8 11:35
 */
public class List转Map测试 {

    static List<Person> persons;
    static{
        persons = Arrays.asList(
                Person.builder().group("1").name("陈小醉").build(),
                Person.builder().group("2").name("李金铭").build(),
                Person.builder().group("3").name("李雅兰").build(),
                Person.builder().group("4").name("李梦君").build(),
                Person.builder().group("5").name("鞠婧祎").build(),
                Person.builder().group("5").name("刘亦菲").build(),
                Person.builder().group("5").name("武则天").build()
        );
    }
    @Test
    public void 测试1(){
        HashMap<String, List<Person>> map = persons.stream().collect(
                Collectors.toMap(
                        Person::getGroup,
                        p -> {List<Person> list = new ArrayList<>();list.add(p);return list;},
                        (u, v) -> {u.addAll(v);return u;},
                        () -> new HashMap<String, List<Person>>())
        );

        map.keySet().stream().forEach(k-> System.out.println(map.get(k)));
    }

    @Test
    public void ceshi2(){
        Map<String, List<Person>> map = persons.stream().collect(Collectors.groupingBy(Person::getGroup));
        map.keySet().stream().forEach(k-> System.out.println(map.get(k)));
    }


    @Test
    public void ceshi3(){
        Map<String, List<String>> map = persons.stream().collect(Collectors.groupingBy(Person::getGroup, Collectors.mapping(Person::getName, Collectors.toList())));
        map.keySet().stream().forEach(k-> System.out.println(map.get(k)));
    }

    @Test
    public void formatTest(){
        System.out.println(String.format("%s","哈哈"));
    }


    @Data
    @Builder
    static class Person{
        private String group;
        private String name;
    }
}
